<template>
  <div class="app-container">
    <basics-form
      ref="basicsForm"
      :minWidth="'300px'"
      :actionLoading="loading"
      @actionBtnsClick="actionBtnsClick"
      @selectCallback="selectCallback"
      @submit="search"
    />
    <el-table
      v-loading="tableLoading"
      :data="tableData"
      border
      stripe
      style="width: 100%"
    >
      <el-table-column prop="name" label="姓名"> </el-table-column>
      <el-table-column prop="phone" label="手机号"> </el-table-column>
      <el-table-column prop="jobNo" label="工号"> </el-table-column>
      <el-table-column prop="departmentName" label="科室"> </el-table-column>
      <el-table-column prop="postName" label="职务"> </el-table-column>
      <el-table-column prop="occupationStartYear" label="职业起始年份">
      </el-table-column>
      <el-table-column label="性别">
        <template slot-scope="scope">
          <span>{{
            scope.row.sex == 1 ? "男" : scope.row.sex == 0 ? "女" : "未知"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        fixed="right"
        width="190px"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="roleId==3"
            @click="showDetails(scope.row)"
            >修改</el-button
          ><el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="showEvaluate(scope.row)"
            >患者评价</el-button
          >
          <el-popconfirm
            style="margin-left: 10px"
            title="确定删除吗？"
            v-if="roleId==3"
            @confirm="del(scope.row.doctorId)"
          >
            <el-button
              slot="reference"
              size="mini"
              type="text"
              icon="el-icon-delete"
              >删除</el-button
            >
          </el-popconfirm>
          <!-- <el-dropdown
            size="mini"
            @command="(command) => handleCommand(command, scope.row)"
          >
            <span class="el-dropdown-link">
              <i class="el-icon-d-arrow-right el-icon--right"></i>更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleDataScope" icon="el-icon-search"
                >他的患者</el-dropdown-item
              >
              <el-dropdown-item command="handleAuthUser" icon="el-icon-search"
                >提醒记录</el-dropdown-item
              >
              <el-dropdown-item command="handleAuthUser" icon="el-icon-search"
                >关怀记录</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown> -->
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="$refs.basicsForm.formValid()"
    />

    <el-dialog
      :title="item ? '修改' : batch ? '批量导入' : '新增'"
      :visible.sync="openView"
      :width="batch ? '700px' : '1200px'"
      append-to-body
    >
      <span
        style="color: rgb(3, 167, 240); cursor: pointer"
        @click="down"
        v-if="batch"
        >点击下载模板</span
      >
      <basics-form
        :style="{ marginLeft: batch ? '100px' : '0px' }"
        ref="basicsAddForm"
        :minWidth="'400px'"
        :titleAligin="'right'"
        :titleWidth="'130px'"
        :actionLoading="loading"
        @actionBtnsClick="addAction"
        @submit="addSubmit"
      />
    </el-dialog>
    <el-dialog
      title="患者评价"
      :visible.sync="evaluateView"
      width="1200px"
      append-to-body
    >
      <evaluate ref="evaluate"/>
    </el-dialog>
  </div>
</template>

<script>
import BasicsForm from "@/components/BasicsForm";
import Evaluate from "./evaluate";
import {
  dictDataForDoctor,
  doctorList,
  saveDoctor,
  delDoctor,
} from "@/api/manbing/doctor";
import { hospitalAllList } from "@/api/manbing/hospital";

export default {
  name: "Doctor",
  components: { BasicsForm,Evaluate },
  data() {
    return {
      roleId: sessionStorage.getItem("roleId"),
      batch: false,
      loading: false,
      tableLoading: false,
      openView: false, //新增医院弹出
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      tableData: [],
      item: null, //操作的数据
      hospitals: null,
      hospitalIndex: 0,
      dictData: null, //职务和科室下拉字典数据
      evaluateView:false,//患者评价弹出
    };
  },
  created() {
    this.$nextTick(() => {
      if (this.roleId != 3) {
        this.getHospitals();
      } else {
        this.getDictDataForDoctor();
      }
    });
  },
  methods: {
    getHospitals() {
      if (this.hospitals) {
        this.getDictDataForDoctor();
      } else {
        hospitalAllList({}).then((res) => {
          if (res.code == 200) {
            this.hospitals = res.data;
            this.getDictDataForDoctor();
          }
        });
      }
    },
    //职务和科室下拉字典数据
    getDictDataForDoctor(changeFlag) {
      if ((this.roleId != 3 && this.hospitals.length) || this.roleId == 3) {
        let data = {};
        if (this.roleId != 3 && this.hospitals.length) {
          data.deptId = this.hospitals[this.hospitalIndex].deptId;
        }
        dictDataForDoctor(data).then((res) => {
          if (res.code == 200) {
            this.dictData = res.data;
            if (changeFlag) {
              this.$refs.basicsForm.changeRulesValue([
                {
                  index: 2,
                  key: "selectList",
                  value: this.dictData.departmentList,
                },
                { index: 3, key: "selectList", value: this.dictData.postList },
              ]);
              this.$refs.basicsForm.changeParamValue({
                key: "postId",
                value: "",
              });
              this.$refs.basicsForm.changeParamValue({
                key: "departmentId",
                value: "",
              });
            } else {
              this.initRules();
            }
          }
        });
      }
    },
    initRules() {
      let rules = [
        {
          title: "关键字",
          key: "keyWord",
          placeholder: "姓名/工号/手机号",
          skip: true,
        },
        {
          title: "科室",
          key: "departmentId",
          type: "select",
          selectList: this.dictData.departmentList,
          selectKey: "deptId",
          selectShowKey: "deptName",
          skip: true,
        },
        {
          title: "职务",
          key: "postId",
          type: "select",
          selectList: this.dictData.postList,
          selectKey: "postId",
          selectShowKey: "postName",
          skip: true,
        },
        {
          type: "actionBtns",
          selectList: [
            { name: "搜索", value: "primary" },
          ],
        },
      ];
      if (this.roleId != 3) {
        rules.unshift({
          title: "所属医院",
          key: "deptId",
          type: "select",
          selectList: this.hospitals,
          selectShowKey: "deptName",
          skip: true,
          value: this.hospitalIndex,
          hiddenClose: true,
          callback: true,
        });
      }else{
        rules[rules.length-1].selectList=[
            { name: "搜索", value: "primary" },
            { name: "新增", value: "success" },
            { name: "批量导入", value: "success" },
          ]
      }
      this.$refs.basicsForm.initForm(rules);
      this.$nextTick(() => {
        this.$refs.basicsForm.formValid();
      });
    },
    selectCallback(res) {
      if (res.key == "deptId") {
        this.hospitalIndex = res.value;
        this.getDictDataForDoctor(true);
      }
    },
    actionBtnsClick(index) {
      if (index == 1) {
        this.item = null;
        this.openView = true;
        this.$nextTick(() => {
          this.initAddRules();
        });
      } else if (index == 2) {
        this.item = null;
        this.openView = true;
        this.$nextTick(() => {
          this.initAddRules(true);
        });
      } else {
        this.queryParams.pageNum = 1;
        this.$refs.basicsForm.formValid();
      }
    },
    //搜索
    search(param) {
      if (!param) {
        return;
      }
      for (let key in param) {
        this.queryParams[key] = param[key];
      }
      this.getList();
    },
    getList() {
      this.loading = true;
      this.tableLoading = true;
      doctorList(this.queryParams)
        .then((res) => {
          if (res.code == 200) {
            this.tableData = res.rows;
            this.total = res.total;
          }
        })
        .finally(() => {
          this.loading = false;
          this.tableLoading = false;
        });
    },
    //患者评价
    showEvaluate(item){
      this.evaluateView = true;
      this.$nextTick(() => {
        this.$refs.evaluate.init(item.doctorId);
      });
    },
    showDetails(item) {
      this.openView = true;
      this.item = item;
      this.$nextTick(() => {
        this.initAddRules();
      });
    },
    //batch 是否批量
    initAddRules(batch) {
      this.batch = batch;
      let rules = [],
        item = this.item ? this.item : {},
        departmentIdValue = "",
        postIdValue = "";

      if (item.departmentId) {
        this.dictData.departmentList.some((it, index) => {
          if (it.deptId == item.departmentId) {
            departmentIdValue = index;
            return true;
          }
        });
      }
      if (item.postId) {
        this.dictData.postList.some((it, index) => {
          if (it.postId == item.postId) {
            postIdValue = index;
            return true;
          }
        });
      }
      if (batch) {
        rules = [
          {
            title: "医院",
            key: "hospitalName",
            disabled: true,
            value: this.item
              ? this.item.hospitalName
              : this.roleId == 3
              ? JSON.parse(sessionStorage.getItem("user")).dept.deptName
              : this.hospitals[this.hospitalIndex].deptName,
            skip: true,
          },

          {
            title: "文件",
            key: "file",
            type: "file",
            hidden: !batch,
            uploadAction:
              process.env.VUE_APP_BASE_API +
              "/chronicdisease/hospital/importDoctor",
            submitInUpload: true,
          },
        ];
      } else {
        rules = [
          {
            title: "医院",
            key: "hospitalName",
            disabled: true,
            value: this.item
              ? this.item.hospitalName
              : this.roleId == 3
              ? JSON.parse(sessionStorage.getItem("user")).dept.deptName
              : this.hospitals[this.hospitalIndex].deptName,
            skip: true,
          },
          {
            title: "姓名",
            key: "name",
            value: item.name || "",
          },
          {
            title: "手机号(账号)",
            key: "phone",
            maxlength: 11,
            ruleList: ["isMobile"],
            ruleMsgList: ["请输入正确的手机号码"],
            value: item.phone || "",
            disabled: this.item ? true : false,
            skip: this.item ? true : false,
          },
          {
            title: "工号",
            key: "jobNo",
            skip: true,
            value: item.jobNo || "",
          },
          {
            title: "身份证号",
            key: "idCard",
            ruleList: ["isIdCard"],
            ruleMsgList: ["请输入正确的身份证号"],
            skip: true,
            value: item.idCard || "",
          },

          {
            title: "性别",
            key: "sex",
            type: "radio",
            selectList: [
              { name: "男", value: "1" },
              { name: "女", value: "0" },
            ],
            selectKey: "value",
            skip: true,
            value: item.sex != undefined && item.sex > -1 ? 1 - item.sex : "",
          },
          {
            title: "科室",
            key: "departmentId",
            type: "select",
            selectList: this.dictData.departmentList,
            selectKey: "deptId",
            selectShowKey: "deptName",
            skip: true,
            value: departmentIdValue,
          },
          {
            title: "职务",
            key: "postId",
            type: "select",
            selectList: this.dictData.postList,
            selectKey: "postId",
            selectShowKey: "postName",
            skip: true,
            value: postIdValue,
          },
          {
            title: "职业起始年限",
            key: "occupationStartYear",
            type: "year",
            skip: true,
            value: item.occupationStartYear || "",
          },
          {
            title: "擅长病种",
            key: "goodAtDisease",
            type: "textarea",
            skip: true,
            value: item.goodAtDisease || "",
          },
          {
            title: "专业特长",
            key: "specialty",
            type: "textarea",
            skip: true,
            value: item.specialty || "",
          },
          {
            title: "简介",
            key: "introduction",
            type: "textarea",
            skip: true,
            value: item.introduction || "",
          },
          {
            title: "身份证照片",
            key: "idCardUrl",
            type: "img",
            skip: true,
            uploadExtra: {
              uploadType: 1,
            },
            uploadAction:
              process.env.VUE_APP_BASE_API + "/chronicdisease/plat/uploadFile",
            value: item.idCardUrl || "",
          },
          {
            title: "执业资格证照片",
            key: "certificateUrl",
            type: "img",
            skip: true,
            uploadExtra: {
              uploadType: 1,
            },
            uploadAction:
              process.env.VUE_APP_BASE_API + "/chronicdisease/plat/uploadFile",
            value: item.certificateUrl || "",
          },
        ];
      }
      rules.push({
        type: "actionBtns",
        selectList: [
          { name: "取消", value: "" },
          { name: "提交", value: "primary" },
        ],
        btnsAligin: "center",
        ruleWidth: batch ? "503px" : "100%",
      });
      this.$refs.basicsAddForm.initForm(rules);
    },
    addAction(index) {
      if (index) {
        this.$refs.basicsAddForm.formValid();
      } else {
        this.openView = false;
      }
    },
    addSubmit(param) {
      if (!param) {
        return;
      }
      console.log(param, "addSubmit");
      if (this.batch) {
        this.$modal.msgSuccess("导入成功");
        this.openView = false;
        this.getList();
        return;
      }
      this.loading = true;
      if (this.hospitals) {
        param.hospitalId = this.hospitals[this.hospitalIndex].deptId;
      }
      if (this.item) {
        param.doctorId = this.item.doctorId;
        param.hospitalId = this.item.hospitalId;
      }
      saveDoctor(param)
        .then((res) => {
          if (res.code == 200) {
            this.$modal.msgSuccess(this.item ? "修改成功" : "新增成功");
            this.openView = false;
            this.getList();
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    //删除
    del(doctorId) {
      this.loading = true;
      this.tableLoading = true;
      delDoctor({ doctorId })
        .then((res) => {
          if (res.code == 200) {
            this.$modal.msgSuccess("删除成功");
            this.getList();
          }
        })
        .finally(() => {
          this.loading = false;
          this.tableLoading = false;
        });
    },
    //下载模板
    down() {
      window.open(
        process.env.VUE_APP_BASE_API +
          "/chronicdisease/hospital/downloadDoctorTemplate"
      );
    },
  },
};
</script>
<style scoped lang="scss">
</style>
